<script setup lang="ts">
import {useRoute} from "vue-router";
import {onMounted, reactive, ref, toRefs, watch} from "vue";
import type {User} from "@/models/user";
import {getMatchUserList, getUserInfoList} from "@/api/UserApi";
import {closeToast, showFailToast, showLoadingToast, showNotify, showToast} from "vant";
import UserCardList from "@/components/UserCardList.vue";
import router from "@/router";

const route = useRoute();

const state = reactive({
  userList: [] as User[],
  pageSize: 10,
  pageNum: 1,
})
// 复选框状态
const checked = ref(false);
// 加载状态（区分刷新和初始加载）
const loading = ref(false);

const {userList, pageSize, pageNum} = {...toRefs(state)}


/**
 * 通用数据加载函数
 * 整合两种加载逻辑，减少重复代码
 */
const loadData = async () => {
  loading.value = true;
  showLoadingToast('加载中...');
  try {
    let res;
    if (checked.value) {
      // 心动模式列表
      res = await getMatchUserList(5);
    } else {
      // 普通用户列表（分页）
      res = await getUserInfoList(Number(pageSize.value), Number(pageNum.value));
    }

    // 未登录处理
    if (res.data.code === 40101) {
      showToast('请登录后重试');
      await router.push({
        path: '/user/login',
        query: {redirect: route.fullPath} // 记录当前路径，登录后可跳转回来
      });
      return;
    }

    // 成功响应处理
    if (res.data.code === 0) {
      // 根据接口类型处理数据格式
      state.userList = checked.value
          ? res.data.data
          : res.data.data.records;
    } else {
      // 业务错误处理
      showFailToast(res.data.description || "加载失败");
    }
  } catch (error) {
    console.error("数据加载错误:", error);
    showFailToast("网络异常，加载失败");
  } finally {
    loading.value = false;
    closeToast();
  }
};

// 初始化加载数据
onMounted(async () => {
  await loadData();
});

// 监听复选框变化，自动重新加载数据
watch(checked, (newVal) => {
  loadData();
}, {immediate: false});

const onRefresh = async () => {
  await loadData();
  showNotify({
    type: 'success',
    message: '刷新成功',
    duration: 500
  });
  loading.value = false;
};
</script>

<template>
  <div>
    <van-cell center>
      <template #right-icon>
        <van-switch v-model="checked"/>
      </template>
      <template #title>
        {{ checked === false ? '普通模式' : "心动模式" }}
        <van-icon color="red" v-if="checked" name="like"/>
      </template>
    </van-cell>
  </div>
  <div id="index">
    <div>
            <van-pull-refresh v-model="loading" @refresh="onRefresh">

        <UserCardList :user-list="userList"/>
            </van-pull-refresh>
    </div>

    <div v-if="userList.length < 1 || !userList">
      <van-empty description="数据为空"/>
    </div>
  </div>
</template>

<style scoped>
#index {
  min-height: 100vh;
  padding: 10px;
  box-sizing: border-box;
}
</style>
